#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //设置窗口标题
    this->setWindowTitle("客户端");
    //创建socket对象实例
    socket = new QTcpSocket(this);
    //和服务器建立连接
    socket->connectToHost("47.98.42.43",8889);

    //连接信号槽处理响应
    connect(socket,&QTcpSocket::readyRead,this,[=](){
        //读取响应内容
        QString response = socket->readAll();
        //把响应的内容显示到界面上
        ui->listWidget->addItem("服务器："+response);
    });

    //等待连接建立的结果，确认是否连接成功
    bool r = socket->waitForConnected();
    if(!r)
    {
        QMessageBox::critical(this,"连接输错",socket->errorString());
        exit(1);
    }
    
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    //获取到输入框的内容
    const QString& text = ui->lineEdit->text();
    //发送给服务器
    socket->write(text.toUtf8());
    //把发出的消息显示到界面上
    ui->listWidget->addItem("客户端:"+text);
    ui->lineEdit->setText("");
}
